<template>
    <div class="upload-drop" v-show="showed">
        <div class="upload-drop-text">文件拖放到此处</div>
    </div>
</template>

<script>
export default {
    name: 'upload-drop',
    data() {
        return {
            showed: false
        }
    },
    mounted() {
        this.$nextTick(() => {
            var dnd = document.querySelector('.layout');

            var state = 0;

            dnd.addEventListener('dragenter', (e) => {
                e.preventDefault();
                e.stopPropagation();
                state = 1;
                this.toggleShowBox(true);
            });

            dnd.addEventListener('dragover', (e) => {
                e.preventDefault();
                e.stopPropagation();
                state = 2;
            });

            dnd.addEventListener('dragleave', (e) => {
                if (state === 2) {
                    this.toggleShowBox(false);
                }
                state = 3;
            });

            dnd.addEventListener('drop', (e) => {
                state = 4;
                e.preventDefault();
                e.stopPropagation();
                if (e.dataTransfer.files && e.dataTransfer.files.length) {
                    this.upload(e.dataTransfer.files);
                }
            });
        });
    },
    methods: {
        toggleShowBox(isShow) {
            this.showed = isShow;
        },
        upload(files) {
            this.$emit('dropUpload', files);
            this.showed = false;
        }
    }
}
</script>

<style scoped>
/* 拖拽上传遮罩 */
.upload-drop {
  position: fixed;
  z-index: 9999;
  background-color: rgb(249, 245, 245);
  opacity: 0.2;
  border: 5px dashed;
  top: 0px;
  left: 0px;
  right: 0;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
}
.upload-drop .upload-drop-text {
  top: 50%;
  left: 50%;
  margin-left: -50px;
  margin-top: -50px;
  font-size: 24px;
  opacity: 1;
  position: absolute;
}
</style>
